package com.xuegao.xuegaoremotelogin.mvc;

import com.xuegao.xuegaoremotelogin.constant.Cache;
import com.xuegao.xuegaoremotelogin.domain.UserInfo;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public void afterCompletion(HttpServletRequest request,
                                HttpServletResponse response,
                                Object arg2,
                                Exception arg3)
            throws Exception {
    }

    @Override
    public void postHandle(HttpServletRequest request,
                           HttpServletResponse response,
                           Object arg2,
                           ModelAndView arg3)
            throws Exception {
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object arg2) throws Exception {
        String url = request.getRequestURI();
        System.out.println("=============================");
        System.out.println("LoginInterceptor");
        System.out.println("=============================");
        // 如果拦截到的是登录的页面的话放行
        if (url.indexOf("login") >= 0) {
            return true;
        }
        // 如果是其他请求地址，进行拦截
        UserInfo userInfo = (UserInfo) request.getSession().getAttribute("username");
        if (userInfo != null) {
            String sessionId = request.getSession().getId();
            String mapSessionId = Cache.SESSION_MAP.get(userInfo.getUsername());
            System.out.println("mapSessionId = " + mapSessionId + ", sessionId = " + sessionId);
            // 如果用户名存在放心（即登录放行）
            if (sessionId.equals(mapSessionId)) {
                return true;
            } else {
                //如果请求的sessionID和此账号Map中存放的sessionID不一致，跳转到登陆页
                System.out.println("11111111111");
                response.sendRedirect("/xuegao/login.html");
                return false;
            }
        }

        System.out.println("2222222222");
        // 如果session中没有 userInfo，跳转到登陆页
        response.sendRedirect("/xuegao/login.html");
        return false;
    }

}